package com.api.shopapi.controller;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import com.api.shopapi.common.BatchPushUtil;
import com.api.shopapi.common.IpUtil;
import com.api.shopapi.common.PushtoSingle;
import com.api.shopapi.config.WebSocket;
import com.api.shopapi.entity.Area;
import com.api.shopapi.entity.MyResult;
import com.api.shopapi.entity.PreCheck;
import com.api.shopapi.entity.dto.AreaDTO;
import com.api.shopapi.service.AreaService;
import com.api.shopapi.service.CacheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;


/**
 * 全国地区
 * */

@RestController
@RequestMapping("Area")
public class AreaController extends BaseController {

    @Autowired
    @Qualifier("AreaServiceImplOne")
    private AreaService areaService;

    @Autowired
    @Qualifier("CacheServiceImplOne")
    private CacheService cacheService;

    @Autowired
    WebSocket webSocket;


    //添加菜单
    void AddArea(String parentCode, JSONArray arr, int level) {
        for (int k = 0; k < arr.size(); k++) {
            JSONObject menuDy = arr.getJSONObject(k);
            Area area = new Area();
            area.setAreaCode(menuDy.getString("code"));
            area.setParentAreaCode(menuDy.getString("parentCode"));
            area.setName(menuDy.getString("name"));
            area.setSort(0);
            area.setLevel(level);
            area.setStatus(0);
            areaService.insert(area);
            //添加子级菜单
            JSONArray listMenuDy = menuDy.getJSONArray("listMenu");
            if (listMenuDy != null) {
                AddArea(menuDy.getString("code"), listMenuDy, level + 1);
            }
        }
    }

    //编辑全部的菜单
    @RequestMapping(value = "Init", method = RequestMethod.POST)
    public MyResult Init(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");
            JSONArray listMenu = jsonObject.getJSONArray("listMenu");

            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/Area/Init");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            if (listMenu != null) {
                AddArea(emptyUUID, listMenu, 0);
            }

            Object data = new Object[]{};
            return success(data);
        } catch (Exception e) {
            insertError("/Area/Init", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(e.getMessage());
        }
    }

    List<AreaDTO> getListAreaDTO() {
        List<Area> listArea = areaService.getListByParentAreaCode(emptyUUID);
        List<AreaDTO> listAreaDTO = new ArrayList<AreaDTO>();
        for (Area area : listArea) {
            AreaDTO areaDTO = mapper.map(area, AreaDTO.class);
            listAreaDTO.add(areaDTO);
        }

        for (AreaDTO areaDTO : listAreaDTO) {
            List<Area> listArea2 = areaService.getListByParentAreaCode(areaDTO.getAreaCode());
            List<AreaDTO> listAreaDTO2 = new ArrayList<AreaDTO>();

            for (Area area : listArea2) {
                AreaDTO areaDTO2 = mapper.map(area, AreaDTO.class);
                listAreaDTO2.add(areaDTO2);
            }

            for (AreaDTO areaDTO2 : listAreaDTO2) {
                List<Area> listArea3 = areaService.getListByParentAreaCode(areaDTO2.getAreaCode());
                List<AreaDTO> listAreaDTO3 = new ArrayList<AreaDTO>();
                for (Area area : listArea3) {
                    AreaDTO areaDTO3 = mapper.map(area, AreaDTO.class);
                    listAreaDTO3.add(areaDTO3);
                }

                for (AreaDTO areaDTO3 : listAreaDTO3) {
                    List<Area> listArea4 = areaService.getListByParentAreaCode(areaDTO3.getAreaCode());
                    List<AreaDTO> listAreaDTO4 = new ArrayList<AreaDTO>();
                    for (Area area : listArea4) {
                        AreaDTO areaDTO4 = mapper.map(area, AreaDTO.class);
                        listAreaDTO4.add(areaDTO4);
                    }

                    for (AreaDTO areaDTO4 : listAreaDTO4) {
                        List<Area> listArea5 = areaService.getListByParentAreaCode(areaDTO4.getAreaCode());
                        List<AreaDTO> listAreaDTO5 = new ArrayList<AreaDTO>();

                        for (Area area : listArea5) {
                            AreaDTO areaDTO5 = mapper.map(area, AreaDTO.class);
                            listAreaDTO5.add(areaDTO5);
                        }
                        areaDTO4.setListAreaDTO(listAreaDTO5);
                    }
                    areaDTO3.setListAreaDTO(listAreaDTO4);
                }
                areaDTO2.setListAreaDTO(listAreaDTO3);
            }
            areaDTO.setListAreaDTO(listAreaDTO2);
        }
        return listAreaDTO;
    }

    //列表
    @RequestMapping(value = "List", method = RequestMethod.POST)
    public MyResult List(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String parentAreaCode = jsonObject.getString("parentAreaCode");

            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/Area/List");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            List<Area> listArea = areaService.getListByParentAreaCode(parentAreaCode);
            return success(listArea);
        } catch (Exception e) {
            insertError("/Area/List", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }

    //列表
    @RequestMapping(value = "ListAll", method = RequestMethod.POST)
    public MyResult ListAll(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");

            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/Area/ListAll");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            if (cacheService.getCacheDataByKey("listAreaDTO") == null) {

                System.out.println("-----------putCache---------listAreaDTO----------------");

                cacheService.clearByKey("listAreaDTO");
                cacheService.putCache("listAreaDTO", getListAreaDTO(), 0);
            }
            List<AreaDTO> listAreaDTO = (List<AreaDTO>) cacheService.getCacheDataByKey("listAreaDTO");
            return success(listAreaDTO);
        } catch (Exception e) {
            insertError("/Area/ListAll", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }

    //添加
    @RequestMapping(value = "Add", method = RequestMethod.POST)
    public MyResult Add(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String parentAreaCode = jsonObject.getString("parentAreaCode");
            String name = jsonObject.getString("name");
            int sort = jsonObject.getInteger("sort");

            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/Area/Add");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }
            int parentLevel = 0;
            Area area = areaService.getByAreaCode(parentAreaCode);
            if (area != null) {
                parentLevel = area.getLevel() + 1;
            }
            Area area1 = new Area();
            area1.setAreaCode(UUID.randomUUID().toString());
            area1.setParentAreaCode(parentAreaCode);
            area1.setName(name);
            area1.setSort(sort);
            area1.setLevel(parentLevel);
            area1.setStatus(0);
            areaService.insert(area1);
            cacheService.clearByKey("listAreaDTO");
            cacheService.putCache("listAreaDTO", getListAreaDTO(), 0);
            Object object = new Object[]{};
            return success(object);
        } catch (Exception e) {
            insertError("/Area/Add", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }

    //修改
    @RequestMapping(value = "Edit", method = RequestMethod.POST)
    public MyResult Edit(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String areaCode = jsonObject.getString("areaCode");
            String name = jsonObject.getString("name");
            int sort = jsonObject.getInteger("sort");
            int status = jsonObject.getInteger("status");

            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/Area/Edit");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }
            Area area = areaService.getByAreaCode(areaCode);
            area.setName(name);
            area.setSort(sort);
            area.setStatus(status);
            areaService.updateByAreaCode(area);
            cacheService.clearByKey("listAreaDTO");
            cacheService.putCache("listAreaDTO", getListAreaDTO(), 0);
            Object object = new Object[]{};
            return success(object);
        } catch (Exception e) {
            insertError("/Area/Edit", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }

    }

    //获取位置根据经纬度(腾讯)
    @RequestMapping(value = "GetAddressByLonLat", method = RequestMethod.POST)
    public MyResult GetAddressByLonLat(@RequestBody JSONObject jsonObject) {

        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");

            String lonStart = jsonObject.getString("lonStart");
            String latStart = jsonObject.getString("latStart");

            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/Area/GetAddressByLonLat");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }


            String addressObject = getAddressByLonLat(lonStart, latStart);
            //System.out.println(addressObject);
            JSONObject jsonObjectAddress = JSONObject.parseObject(addressObject);
            String address = "";
            if (jsonObjectAddress.getInteger("status") == 0) {
                address = jsonObjectAddress.getJSONObject("result").getString("address");


                JSONObject result = jsonObjectAddress.getJSONObject("result");
                Object address_reference = result.get("address_reference");
                if (address_reference != null) {
                    Object landmark_l1 = ((JSONObject) address_reference).get("landmark_l1");
                    if (landmark_l1 != null) {
                        address = ((JSONObject) landmark_l1).getString("title");
                    }
                    Object landmark_l2 = ((JSONObject) address_reference).get("landmark_l2");
                    if (landmark_l2 != null) {
                        address = ((JSONObject) landmark_l2).getString("title");
                    }
                }

            }


            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("address", address);
            return success(jsonObject1);

        } catch (Exception e) {
            insertError("/Area/GetAddressByLonLat", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }

    }


    //获取外网IP
    @RequestMapping(value = "GetOutIp", method = RequestMethod.POST)
    public MyResult GetOutIp(@RequestBody JSONObject jsonObject) {

        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");

            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/Area/GetOutIp");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }
            return success(IpUtil.getV4IP());
        } catch (Exception e) {
            insertError("/Area/GetOutIp", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }


    //-------------test--------------------

    @RequestMapping(value = "test", method = RequestMethod.POST)
    public void aa(@RequestBody JSONObject jsonObject) {
        String timeStr = jsonObject.getString("timeStr");
        String sign = jsonObject.getString("sign");
        String message = jsonObject.getString("message");
        String code = jsonObject.getString("code");
        webSocket.sendInfoToOne(code,message);
    }

    @RequestMapping(value = "test1", method = RequestMethod.POST)
    public void aa1(@RequestBody JSONObject jsonObject) {
        String timeStr = jsonObject.getString("timeStr");
        String sign = jsonObject.getString("sign");
        String message = jsonObject.getString("message");
        String code = jsonObject.getString("code");
        webSocket.sendInfoToAll(message);
    }

    @RequestMapping(value = "get", method = RequestMethod.GET)
    public String get() {
        return "get";
    }


}
